package com.jshan.blog.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jshan.blog.base.admin.dto.SysRoleResDto;
import com.jshan.blog.base.admin.entity.*;
import com.jshan.blog.converts.RoleAndRoleDtoConvert;
import com.jshan.blog.enums.BizCodeEnums;
import com.jshan.blog.enums.TagInfoEnum;
import com.jshan.blog.mapper.SysRoleMapper;
import com.jshan.blog.result.Result;
import com.jshan.blog.service.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Set;

/**
 * @author jshan
 * @description 针对表【sys_role(系统角色表)】的数据库操作Service实现
 * @createDate 2025-01-16 16:47:01
 */
@Service
@Slf4j
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole>
        implements SysRoleService {

    @Resource
    private SysDictService dictService;
    @Resource
    private SysRoleDictService roleDictService;
    @Resource
    private SysRoleMenuService roleMenuService;
    @Resource
    private SysUserService userService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean saveRoleDto(SysRoleResDto sysRoleResDto) {
        try {
            SysRole role = RoleAndRoleDtoConvert.INSTANCE.RoleDto2RoleConvert(sysRoleResDto);
            LocalDateTime currentTime = LocalDateTime.now();
            role.setCreateTime(currentTime);
            SysDict sysDict = new SysDict();
            sysDict.setSysDictTypeId(TagInfoEnum.USER_TAG.getCode());
            sysDict.setCodeName(role.getRoleName());
            sysDict.setRemark(role.getRemark());
            this.save(role);
            dictService.save(sysDict);
            SysRoleDict sysRoleDict = new SysRoleDict();
            sysRoleDict.setRoleId(role.getId());
            sysRoleDict.setTagId(sysDict.getId());
            return roleDictService.save(sysRoleDict);
        } catch (Exception e) {
            log.error("saveRoleDto:{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public Boolean updateDto(SysRoleResDto sysRoleResDto) {
        SysRole role = RoleAndRoleDtoConvert.INSTANCE.RoleDto2RoleConvert(sysRoleResDto);
        role.setUpdateTime(LocalDateTime.now());
        role.setUpdateId(StpUtil.getLoginIdAsInt());
        SysRoleDict one = roleDictService.getOne(new LambdaQueryWrapper<SysRoleDict>().eq(SysRoleDict::getRoleId, role.getId()));
        SysDict sysDict = new SysDict();
        sysDict.setId(one.getTagId());
        sysDict.setCodeName(role.getRoleName());
        sysDict.setUpdateId(StpUtil.getLoginIdAsInt());
        sysDict.setUpdateTime(LocalDateTime.now());
        dictService.updateById(sysDict);
        return this.updateById(role);
    }

    @Override
    public Page<SysRoleResDto> pageAll(Page<?> page) {
        return baseMapper.pageAll(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result removeRole(Integer id) {
        if (id != null) {
            SysRoleDict roleDic = roleDictService.getOne(new LambdaQueryWrapper<SysRoleDict>().eq(SysRoleDict::getRoleId, id));
            SysDict dictInfo = dictService.getById(roleDic.getTagId());
            if ("管理员".equals(dictInfo.getCodeName())){
                return Result.fail(BizCodeEnums.FAILE.getCode(), "管理员角色不能删除");
            }
            if (userService.count(new LambdaQueryWrapper<SysUser>().eq(SysUser::getUserTagCd, roleDic.getTagId()))>0){
                return Result.fail(BizCodeEnums.FAILE.getCode(), "请先删除对应的用户");
            }
            if (dictService.removeById(roleDic.getTagId())) {
                if (roleDictService.remove(new LambdaQueryWrapper<SysRoleDict>().eq(SysRoleDict::getRoleId, id))) {
                    this.removeById(id);
                    return Result.ok(BizCodeEnums.SUCCESS.getCode(), "删除角色成功");
                }
            }
        }
        return Result.fail(BizCodeEnums.FAILE.getCode(), "删除失败");
    }

    @Override
    public Boolean addMenuIds(Integer roleId, Set<Integer> ids) {
        String str = "";
        if (CollectionUtils.isNotEmpty(ids)) {
            str = ids.stream()
                    .map(String::valueOf)
                    .reduce((a, b) -> a + "," + b)// 合并字符串
                    .orElse(""); // 默认值转为空字符串
        }
        SysRoleMenu roleMenu = new SysRoleMenu();
        roleMenu.setRoleId(roleId);
        roleMenu.setMenuId(str);
        return roleMenuService.saveOrUpdate(roleMenu);
    }

}




